#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import COOPGIS_FormMisc
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def GetAndSetDefaultMap(form, ApplicationName, UserName):
    if(form.data.has_key('Map')):    
        try:
            applicationDefaultMap=ApplicationDefaultMap.objects.filter(UserName=UserName, ApplicationName=ApplicationName)[0]
            applicationDefaultMap.Map=Map.objects.filter(id=form.data['Map'])[0]
            applicationDefaultMap.save()
        except:
            applicationDefaultMap=ApplicationDefaultMap()
            applicationDefaultMap.UserName=UserName
            applicationDefaultMap.ApplicationName=ApplicationName
            applicationDefaultMap.Map=Map.objects.filter(id=form.data['Map'])[0]
            applicationDefaultMap.save()

def SetSelectionStationAndSpan(form):
    #Set the Selection Station and Span
    SelectGPSIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'SelectGPSIndicator')
    SelectStationTagNumber=COOPGIS_FormMisc.FormGetString(form, 'SelectStationTagNumber')
    SelectStationid=COOPGIS_FormMisc.FormGetString(form, 'SelectStationid')
    SelectSpanid=COOPGIS_FormMisc.FormGetString(form, 'SelectSpanid')

    SelectionStation=None
    SelectionSpan=None
    GPSStatus=''
    if(SelectGPSIndicator):
         SelectionStation, SelectionSpan, GPSStatus=COOPGIS_GPS.GetNearbyStationandSpanFromGPS()
         try:
             SelectStationid=SelectionStation.id
         except:
             SelectStationid = None
         try:
             SelectSpanid=SelectionSpan.id
         except: 
             SelectSpanid=None
         SelectStationTagNumber = ''
    elif(SelectStationid):
        try:
            SelectionStation=Station.objects.filter(id=SelectStationid)[0]
        except:
            SelectionStation = None
        if(SelectionStation):
            SelectStationTagNumber=''
    elif(SelectStationTagNumber):
        try:
            try:
                SelectionStation=Assembly.objects.filter(TagNumber__exact=SelectStationTagNumber)[0].Station
            except:
                SelectionStation=Assembly.objects.filter(TagNumber__startswith=SelectStationTagNumber)[0].Station
        except:
            SelectionStation = None
        if(SelectionStation):
            SelectionStationid=''
    if(not SelectionSpan):
        try:
            SelectionSpan=Span.objects.filter(id=SelectSpanid)[0]
        except:
            SelectionSpan = None
    try:
        SelectSpanid=SelectionSpan.id
    except:
        SelectSpanid=''
    if(not SelectionStation):
        SelectStationTagNumber = ''
        SelectStationid = ''
    form.data['SelectStationTagNumber'] = SelectStationTagNumber
    form.data['SelectStationid'] = SelectStationid
    form.data['SelectSpanid'] = SelectSpanid
    if(SelectionStation):  
        form.data['SelectGPSIndicator']=False
    return SelectionStation, SelectionSpan, GPSStatus

def SetSelectionStationAndSpanOutdoorLighting(form):
    SelectRoadName=COOPGIS_FormMisc.FormGetString(form, 'SelectRoadName')
    SelectMeterNumber=COOPGIS_FormMisc.FormGetString(form, 'SelectMeterNumber')
    SelectDCSINumber=COOPGIS_FormMisc.FormGetString(form, 'SelectDCSINumber')
    Station, Span, GPS = SetSelectionStationAndSpan(form)
    if Station:
        return Station, Span, GPS
    GPS = ''
    Station, Span = SetSelectionStationAndSpanByMeter(form)
    if Station:
        return Station, Span, GPS
    Station, Span = SetSelectionStationAndSpanByRoad(form)
    return Station, Span, GPS

    


def SetSelectionStationAndSpanTryCircuitNumber(form):
    if form.data.has_key('SelectCircuitNumber') and form.data['SelectCircuitNumber']:
        Assemblies=Assembly.objects.filter(CircuitNumber=form.data['SelectCircuitNumber']).exclude(
            Station__isnull=True)
        StationsIdentifiers=Assemblies.values_list('Station', flat=True).distinct()
        Stations=Station.objects.filter(id__in=list(StationIdentifiers))
        return ''
    else:
        return SetSelectionStationAndSpan(form)


def SetSelectionStationAndSpanByOldMapNumber(form, SelectionStation=None, SelectionSpan=None):
    if(form.data.has_key('OldMapNumber') and form.data['OldMapNumber']):
        try:
            try:
                assembly=Assembly.objects.all().filter(OldMapNumber__iexact=form.data['OldMapNumber'])[0]
            except:
                assembly=Assembly.objects.all().filter(OldMapNumber__istartswith=form.data['OldMapNumber'])[0]
        except:
            assembly = None
            form.data['OldMapNumber'] = ''
    else:
        assembly=None
    if(assembly):
        if(assembly.Station):
            SelectionStation=assembly.Station
            SelectionSpan=None
        elif(assembly.Span):
            SelectionStation=None
            SelectionSpan=assembly.Span
    return SelectionStation, SelectionSpan


def SetSelectionStationAndSpanByRoad(form, SelectionStation=None, SelectionSpan=None):
    if(form.data.has_key('RoadName') and form.data['RoadName']):
        try:
            try:
                road=Road.objects.all().filter(Name__iexact=form.data['RoadName'])[0]
            except:
                road=Road.objects.all().filter(Name__istartswith=form.data['RoadName'])[0]
        except:
            road = None
            assembly=None
        if(road):
            assembly=road.GetNearbyPole()
    else:
        assembly=None
    if(assembly):
        if(assembly.Station):
            SelectionStation=assembly.Station
            SelectionSpan=None
        elif(assembly.Span):
            SelectionStation=None
            SelectionSpan=assembly.Span
    return SelectionStation, SelectionSpan


def SetSelectionStationAndSpanByMeter(form, SelectionStation=None, SelectionSpan=None):
    #raise(Exception(form.data['SelectMeterNumber']))
    if(form.data.has_key('SelectMeterNumber') and form.data['SelectMeterNumber']):
        try:
            try:
                assembly=Assembly.objects.all().filter(MeterNumber__iexact=form.data['SelectMeterNumber'])[0]
            except:
                assembly=Assembly.objects.all().filter(MeterNumber__istartswith=form.data['SelectMeterNumber'])[0]
        except:
            assembly=None
    elif(form.data.has_key('SelectDCSINumber') and form.data['SelectDCSINumber']):
        try:
            try:
                assembly=Assembly.objects.all().filter(MeterDCSINumber__iexact=form.data['SelectDCSINumber'])[0]
            except:
                assembly=Assembly.objects.all().filter(MeterDCSINumber__istartswith=form.data['SelectDCSINumber'])[0]
        except:
            assembly=None
    else:
        assembly=None
    if(assembly):
        if(assembly.Station):
            SelectionStation=assembly.Station
            SelectionSpan=None
        elif(assembly.Span):
            SelectionStation=None
            SelectionSpan=assembly.Span
    return SelectionStation, SelectionSpan



def CreateStation(form, SelectionStation, SelectionSpan, UserName):
    GPSStatus2=''
    try:
        CreateStationIndicator=bool(form.data['CreateStationIndicator'] == 'on')
    except:
        CreateStationIndicator=False
    if(CreateStationIndicator):
        StartPoint, GPSStatus2=COOPGIS_GPS.GetGPSPoint(djangoproject.settings.COOPGISGPSFileName)
        NoGPSNoStation=False
        if(not StartPoint and SelectionStation):  #Meaning No GPS Reading, but a station is selected
            StartPoint=Point(x=SelectionStation.Point.x, y=SelectionStation.Point.y, srid=SelectionStation.Point.srid)
            DistanceNorth=25 * djangoproject.settings.COOPGISDistanceMultiplier
            StartPoint.y = StartPoint.y + DistanceNorth
            while(Station.objects.filter(Point__distance_lte=(StartPoint, 1 * djangoproject.settings.COOPGISDistanceMultiplier))):  #Do Not Allow Stations Closer than this
                DistanceNorth = DistanceNorth + (10 * djangoproject.settings.COOPGISDistanceMultiplier)
                StartPoint.y = StartPoint.y +  (10 * djangoproject.settings.COOPGISDistanceMultiplier)
        elif(not StartPoint):
            NoGPSNoStation=True
        if(not NoGPSNoStation):
            command=Command()
            command=command.Create(Name='CreateStation', StartPoint=StartPoint, CommandUserName=UserName)
            newStation=command.Process()
            SelectStationid= newStation.id
            SelectionStation, SelectionSpan, SelectStationid, SelectStationTagNumber, SelectSpanid, GPSStatus2=UpdateStationandSpanSelection(False, SelectStationid)
            form.data['SelectStationTagNumber'] = SelectStationTagNumber
            form.data['SelectStationid'] = SelectStationid
            form.data['SelectSpanid'] = SelectSpanid
        form.data['CreateStationIndicator']=False   #Clear the Create Flag
    return SelectionStation, SelectionSpan, GPSStatus2


def UpdateStationandSpanSelection(SelectGPSIndicator, SelectStationid):
    SelectionStation=None
    SelectionSpan=None
    GPSStatus=''
    if(SelectGPSIndicator):
         SelectionStation, SelectionSpan, GPSStatus=GetNearbyStationandSpanFromGPS()
         try:
             SelectStationid=SelectionStation.id
         except:
             SelectStationid = None
         try:
             SelectSpanid=SelectionSpan.id
         except: 
             SelectSpanid=None
         SelectionStationTagNumber = None
    elif(SelectStationid):
        try:
            SelectionStation=Station.objects.filter(id__exact=SelectStationid)[0]
        except:
            SelectionStation = None
        if(SelectionStation):
            SelectTagNumber=''
    elif(SelectTagNumber):
        try:
            try:
                SelectionStation=Assembly.objects.all().filter(TagNumber__exact=SelectTagNumber)[0].Station
            except:
                SelectionStation=Assembly.objects.all().filter(TagNumber__startswith=SelectTagNumber)[0].Station
        except:
            SelectionStation = None
        if(SelectionStation):
            SelectionStationid=''
    if(not SelectionSpan):
        try:
            SelectionSpan=Span.objects.filter(id__exact=SelectSpanid)[0]
        except:
            SelectionSpan = None
    try:
        SelectSpanid=SelectionSpan.id
    except:
        SelectSpanid=''
    if(not SelectionStation):
        SelectTagNumber = ''
        SelectStationid = ''
    return SelectionStation, SelectionSpan, SelectStationid, SelectTagNumber, SelectSpanid, GPSStatus     

def CreateSpan(form, SelectionStation, SelectionSpan, UserName):
    try:
        CreateNewSpanIndicator=bool(form.data['CreateSpanIndicator'] == 'on')
    except:
        CreateNewSpanIndicator=False
    if(CreateNewSpanIndicator and form.data['SpanFarStation'] and SelectionStation):
        try:
            SpanFarStationString=form.data['SpanFarStation']
            if(SpanFarStationString[0] == 'T' or SpanFarStationString[0] == 't'):
                TagAssembly=Assembly.objects.filter(TagNumber__exact=SpanFarStationString[1:])[0]
                SpanFarStationString=str(TagAssembly.Station.id) #If this fails, will fall through to the except and skip the rest of the Far Station Code
            EndStation=Station.objects.all().filter(id=int(SpanFarStationString))[0]
            span=Span()
            try:
                SpanJointTrenchIndicator=bool(form.data['SpanJointTrenchIndicator'] == 'on')
            except:
                SpanJointTrenchIndicator=False
            command=Command()
            command=command.Create(Name='CreateSpan', StartPoint=SelectionStation.Point, EndPoint=EndStation.Point, 
                                   JointTrenchIndicator=SpanJointTrenchIndicator, CommandUserName=UserName)
            newSpan=command.Process()
            form.data['SelectSpanid'] = newSpan.id
            SelectionSpan=newSpan
            form.data['CreateSpanIndicator']=False
            form.data['SpanJointTrenchIndicator'] = False
        except: 
            pass
    return SelectionSpan


def UpdateStationComment(form, SelectionStation, UserName):
    try:
        UpdateStationCommentIndicator=bool(form.data['UpdateStationCommentIndicator'] == 'on')
    except:
        UpdateStationCommentIndicator=False    
    if(SelectionStation and UpdateStationCommentIndicator):
        command=Command()
        command=command.Create(Name='UpdateStationComment', StartPoint=SelectionStation.Point, 
                                Description=form.data['StationComment'], CommandUserName=UserName)
        updateCommentStation=command.Process()
        form.data['UpdateStationCommentIndicator'] = False
    elif(SelectionStation):
        form.data['StationComment'] = SelectionStation.Description
    else:
        form.data['StationComment'] = ''


def UpdateStationTransformerBankType(form, SelectionStation, UserNameOrIPAddress):
    if(not SelectionStation):
        return 
    try:
        transformerBankTypeid=int(form.data['StationTransformerBank'])
    except:
        return 
    if(transformerBankTypeid == -1):  #-1 is code for do nothing
        return 
    if(transformerBankTypeid == -2):  #-2 is code to delete all Transformer Banks associated with the current station  
        TransformerBanks=TransformerBank.objects.filter(Station=SelectionStation)
        for i in TransformerBanks:
            command=Command()
            objectid, objectIndexWhenReverseSorted = i.GetCommandidData()
            command=command.Create(Name='DeleteTransformerBank', Objectid=objectid, ObjectIndexWhenReverseSorted=objectIndexWhenReverseSorted)
            command.Process()
        return 

    try:
        transformerBankType=TransformerBankType.objects.filter(id=transformerBankTypeid)[0]
    except:
        return
    command=Command()
    Stationid, StationIndexWhenReverseSorted=SelectionStation.GetCommandidData()
    command=command.Create(Name='CreateTransformerBank', Description='', TransformerBankTypeName=transformerBankType.Name, Stationid=Stationid, StationIndexWhenReverseSorted=StationIndexWhenReverseSorted)
    command.Process()
   


def UpdateSpanComment(form, SelectionSpan, UserName):
    try:
        UpdateSpanCommentIndicator=bool(form.data['UpdateSpanCommentIndicator'] == 'on')
    except:
        UpdateSpanCommentIndicator=False    
    try:
        SpanTapIndicator=bool(form.data['SpanTapIndicator'] == 'on')
    except:
        SpanTapIndicator=False
    try:
        StakerStopTraceIndicator=bool(form.data['StakerStopTraceIndicator'] == 'on')
    except:
        StakerStopTraceIndicator=False

    if(SelectionSpan and UpdateSpanCommentIndicator):
        command=Command()
        command=command.Create(Name='UpdateSpanComment', StartPoint=SelectionSpan.StartStation.Point, EndPoint=SelectionSpan.EndStation.Point,
                                         Line=SelectionSpan.Line,
                                         Description=form.data['SpanComment'], CommandUserName=UserName, TapIndicator=SpanTapIndicator,
                                         StakerStopTraceIndicator=StakerStopTraceIndicator)
        updatedCommentSpan=command.Process()
        form.data['UpdateSpanCommentIndicator'] = False  
    elif(SelectionSpan):
        form.data['SpanComment'] = SelectionSpan.Description
        form.data['SpanTapIndicator'] = SelectionSpan.TapIndicator
        form.data['StakerStopTraceIndicator'] = SelectionSpan.StakerStopTraceIndicator
    else:
        form.data['SpanComment'] = ''
        form.data['SpanTapIndicator'] = False
        form.data['StakerStopTraceIndicator'] = False

def MoveStation(form, SelectionStation, UserName):
    dx=0
    dy=0
    GPSStatus=''
    try:
        MoveStationGPSIndicator=bool(form.data['MoveStationGPSIndicator'] == 'on')
    except:
        MoveStationGPSIndicator=False
    if(SelectionStation and MoveStationGPSIndicator):
        NewPoint, GPSStatus=COOPGIS_GPS.GetGPSPoint(djangoproject.settings.COOPGISGPSFileName)
        a=str(NewPoint)
        if(NewPoint):
            dx = NewPoint.x - SelectionStation.Point.x
            dy = NewPoint.y - SelectionStation.Point.y
        form.data['MoveStationGPSIndicator']=False    
    #Check to see if the Station should be moved 
    if(not dx and not dy):
        try:
            dy=int(form.data['MoveStationNorth'])
        except:
            dy=0
        try:
            dx=int(form.data['MoveStationEast'])
        except:
            dx=0
    if((dx or dy) and SelectionStation):
        StartPoint=Point(x=SelectionStation.Point.x, y=SelectionStation.Point.y, srid=SelectionStation.Point.srid)
        command=Command()
        command=command.Create(Name='MoveStation', StartPoint=StartPoint, dx=dx, dy=dy, CommandUserName=UserName)
        NewPoint=command.Process()
        form.data['MoveStationNorth']='0'
        form.data['MoveStationEast']='0'
        SelectionStation=Station.objects.filter(id__exact=SelectionStation.id)[0]
    return GPSStatus, SelectionStation

def DeleteStation(form, SelectionStation, UserName):
    StationDeleted=False
    try:
        DeleteStationIndicator=bool(form.data['DeleteStationIndicator'] == 'on')
    except:
        DeleteStationIndicator=False
    if(DeleteStationIndicator and SelectionStation):
        if(SelectionStation.OKToDelete()): 
            command=Command()
            command=command.Create(Name='DeleteStation', StartPoint=SelectionStation.Point, CommandUserName=UserName)
            DeletedStationIndicator = command.Process()
            form.data['DeleteStationIndicator']=False    
            StationDeleted=True
    return StationDeleted

def DeleteURDMarker(form, SelectionStation):
    try:
        RunDeleteURDMarkerStationIndicator=bool(form.data['RunDeleteURDMarkerStationIndicator'] == 'on')
    except:
        RunDeleteURDMarkerStationIndicator=False
    if(RunDeleteURDMarkerStationIndicator and SelectionStation):
        SelectionStation.DeleteURDMarkerStation()

def DeleteSpan(form, SelectionSpan, UserName):
    try:
        DeleteSpanIndicator=bool(form.data['DeleteSpanIndicator'] == 'on')
    except:
        DeleteSpanIndicator=False
    if(DeleteSpanIndicator and SelectionSpan):
        if(SelectionSpan.OKToDelete()):
            Line=fromstr(str(SelectionSpan.Line), srid=djangoproject.settings.COOPGISSRID)
            StartStation=SelectionSpan.StartStation
            EndStation=SelectionSpan.EndStation
            command=Command()
            command=command.Create(Name='DeleteSpan', Line=Line, StartPoint=StartStation.Point, EndPoint=EndStation.Point, CommandUserName=UserName)
            DeletedSpanIndicator=command.Process() 
            form.data['DeleteSpanIndicator']=False



def SetSelectionPoint(form, UserName):
    """SetSelectionPoint sets a point not always linked to a station or span in the SelectionPoint table
       Based on a form, as used initially by RoadEditor"""
    line=COOPGIS_FormMisc.FormGetGeographicData(form, 'Line')  #This value is overwritten if ImportTraceToRoadIndicator is True
    SelectionStationTagNumber=COOPGIS_FormMisc.FormGetString(form, 'SelectionStationTagNumber')
    SelectStationid=COOPGIS_FormMisc.FormGetString(form, 'SelectStationid')
    SelectStationGPSIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'SelectStationGPSIndicator')

    #GPS, TagNumber, Station, line #Each previous entry overrides the later ones
    SelectionPoint.objects.filter(UserName=UserName).delete()
    selectionPoint=SelectionPoint()
    selectionPoint.UserName=UserName
    GPSStatus=''
    FoundValidPoint=False
    if(SelectStationGPSIndicator):
        GPSPoint, GPSStatus=GetGPSPoint(djangoproject.settings.COOPGISGPSFileName)
        if(GPSPoint):
            selectionPoint.Point=GPSPoint
            FoundValidPoint=True
    if(not FoundValidPoint and SelectionStationTagNumber):
        assembly=Assembly.objects.filter(TagNumber=SelectionStationTagNumber).order_by('id')
        if(assembly and assembly[0].Station):
            selectionPoint.Point=assembly[0].Station.Point
            FoundValidPoint=True
    if(not FoundValidPoint and SelectStationid):
        station=Station.objects.filter(id=SelectStationid)
        if(station):
            selectionPoint.Point=station[0].Point
            FoundValidPoint=True
    if(not FoundValidPoint and line):
        try:
            selectionPoint.Point=Point(x=line.coords[0][0], y=line.coords[0][1], 
                                       srid=djangoproject.settings.COOPGISGPSSRID)
            FoundValidPoint=True
        except:
            selectionPoint.Point=None
            FoundValidPoint=False
    #Get the Selection Point Now
    if FoundValidPoint:
        selectionPoint.save()
    else:
        selectionPoint=None
    return selectionPoint, GPSStatus

def BuildGPSTraceForm(DefaultMap):
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all().order_by('Name')
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    Dict['EraseIndicator']=forms.BooleanField()
    Dict['MoveIndicator']=forms.BooleanField()
    Dict['MoveStart']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['MoveEnd']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['MoveNorth']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['MoveEast']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['ReorderIndicator']=forms.BooleanField()
    Dict['ReorderStart']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['ReorderEnd']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['ReorderInsertionPosition']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['DeleteIndicator']=forms.BooleanField()
    Dict['DeleteStart']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['DeleteEnd']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['ManualInsertIndicator']=forms.BooleanField()
    Dict['ManualInsertPosition']=forms.CharField(max_length=25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['ManualInsertLatitude']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['ManualInsertLongitude']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    return Dict


def ProcessGPSTraceForm(form):
    EraseIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'EraseIndicator')
    MoveIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'MoveIndicator')
    MoveStart=COOPGIS_FormMisc.FormGetInteger(form, 'MoveStart', 0)
    MoveEnd=COOPGIS_FormMisc.FormGetInteger(form, 'MoveEnd', 0)
    MoveNorth=COOPGIS_FormMisc.FormGetFloat(form, 'MoveNorth', 0)
    MoveEast=COOPGIS_FormMisc.FormGetFloat(form, 'MoveEast', 0)
    ReorderIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ReorderIndicator')
    ReorderStart=COOPGIS_FormMisc.FormGetInteger(form, 'ReorderStart', 0)
    ReorderEnd=COOPGIS_FormMisc.FormGetInteger(form, 'ReorderEnd', 0)
    ReorderInsertionPosition=COOPGIS_FormMisc.FormGetInteger(form, 'ReorderInsertionPosition', 0)
    DeleteIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeleteIndicator')
    DeleteStart=COOPGIS_FormMisc.FormGetInteger(form, 'DeleteStart')
    DeleteEnd=COOPGIS_FormMisc.FormGetInteger(form, 'DeleteEnd')
    ManualInsertIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ManualInsertIndicator')
    ManualInsertPosition=COOPGIS_FormMisc.FormGetInteger(form, 'ManualInsertPosition', 0)
    ManualInsertLatitude=COOPGIS_FormMisc.FormGetFloat(form, 'ManualInsertLatitude', 0)
    ManualInsertLongitude=COOPGIS_FormMisc.FormGetFloat(form, 'ManualInsertLongitude', 0)
    if(EraseIndicator):
        GPSTrace.objects.all().delete()
        return
    if(MoveIndicator and (MoveEast or MoveNorth)):
        if(MoveEnd):
            Objects=GPSTrace.objects.filter(Order__gte=MoveStart).filter(Order__lte=MoveEnd)
        else:
            Objects=GPSTrace.objects.filter(Order__exact=MoveStart)
        for i in Objects:
            i.Point.x = i.Point.x + MoveEast
            i.Point.y = i.Point.y + MoveNorth
            i.save()
    if(ReorderIndicator and ReorderInsertionPosition and ReorderStart):
        if(ReorderEnd):
            InsertObjects=GPSTrace.objects.filter(Order__gte=ReorderStart).filter(Order__lte=ReorderEnd).order_by('Order')
        else:
            InsertObjects=GPSTrace.objects.filter(Order__gte=ReorderStart).order_by('Order')
        BeforeObjects=GPSTrace.objects.filter(Order__lt=ReorderStart).order_by('Order')
        if(ReorderEnd):
            AfterObjects=GPSTrace.objects.filter(Order__gt=ReorderEnd).order_by('Order')
        else:
            AfterObjects=[]
        CurrentOrder = 5
        for i in BeforeObjects:
            i.Order=CurrentOrder
            i.save()
            CurrentOrder=CurrentOrder+5
        for i in InsertObjects:
            i.Order=CurrentOrder
            i.save()
            CurrentOrder=CurrentOrder+5
        for i in AfterObjects:
            i.Order=CurrentOrder
            i.save()
            CurrentOrder=CurrentOrder+5
    if(DeleteIndicator and DeleteStart and DeleteEnd):
        GPSTrace.objects.filter(Order__gte=DeleteStart).filter(Order__lte=DeleteEnd).delete()
    if(ManualInsertIndicator and ManualInsertPosition and ManualInsertLatitude and ManualInsertLongitude):
        New=GPSTrace()
        New.Point=Point(x=ManualInsertLongitude, y=ManualInsertLatitude, srid=djangoproject.settings.COOPGISGPSSRID)
        PotentialConflict=GPSTrace.objects.filter(Order=ManualInsertPosition)
        if(PotentialConflict):
            PotentialConflict[0].Order = PotentialConflict[0].Order + 1
            PotentialConflict[0].save()
        Objects=GPSTrace.objects.filter(Order__gte=ManualInsertPosition).order_by('-Order')
        for i in Objects:
            i.Order=i.Order + 5
            i.save()
        try:
            New.Order=i.Order - 5
        except:
            New.Order=5
        New.save()

def PopulateGPSTraceForm(form):
    form.data['EraseIndicator']=False
    form.data['MoveIndicator']=False
    form.data['MoveStart']=''
    form.data['MoveEnd']=''
    form.data['MoveNorth']=''
    form.data['MoveEast']=''
    form.data['ReorderIndicator']=False
    form.data['ReorderStart']=''
    form.data['ReorderEnd']=''
    form.data['ReorderInsertionPosition']=''
    form.data['DeleteIndicator']=False
    form.data['DeleteStart']=''
    form.data['DeleteEnd']=''
    form.data['ManualInsertIndicator']=False
    return form




def GetGridInfo(form, station):
    if(not station or not COOPGIS_FormMisc.FormGetBoolean(form, 'ShowGridInfoIndicator')):
        return None, None, None
    point=station.Point
    try:
        CurrentGridSquare=Grid.objects.filter(Border__contains=point).filter(SubGridIndicator=True)[0]
    except:
        CurrentGridSquare=None
    if(not CurrentGridSquare):
        try:
            CurrentGridSquare=Grid.objects.filter(Border__contains=point)[0]
        except:
            CurrentGridSquare=None
    if(not CurrentGridSquare):  #No info to return if not in the grid
        return None, None, None
    Stations=Station.objects.filter(Point__within=CurrentGridSquare.Border)
    Meters=[]
    for i in Stations:
        Assemblies=Assembly.objects.filter(Station=i).filter(CompatibleUnit__MeterIndicator=True)
        for assembly in Assemblies:
            Meters.append([assembly.OldMapNumber, assembly.Station.id])
    Meters.sort(key=lambda x: x[0]) #FIXME Need to sort by the last digit of the map number after the 1st 2
    CurrentGridMeters=Assembly.objects.filter(CompatibleUnit__MeterIndicator=True).filter(OldMapNumber__startswith=CurrentGridSquare.Name)
    MapNumbersWithStationAndMap=[]
    for assembly in CurrentGridMeters:
        try:
            CurrentAssemblyGridSquare=Grid.objects.filter(Border__contains=assembly.Station.Point).filter(SubGridIndicator=True)[0]
        except:
            CurrentAssemblyGridSquare=None
        if(not CurrentAssemblyGridSquare):
            try:
                CurrentAssemblyGridSquare=Grid.objects.filter(Border__contains=point)[0]
            except:
                CurrentAssemblyGridSquare=None
        if(CurrentAssemblyGridSquare):
            GridSquareName=CurrentAssemblyGridSquare.Name
        else:
            GridSquareName='Not in the Grid System'
        MapNumbersWithStationAndMap.append([assembly.OldMapNumber, assembly.Station.id, GridSquareName])
    return CurrentGridSquare.Name, Meters, MapNumbersWithStationAndMap



      

